package lib.wzh.com.libcore.framework.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @Author lib
 * @Date 2021/12/29 9:08
 * @ClassName RedisUtil
 * @Version v1.0
 */

@Component
public class RedisUtil {

    private RedisUtil(){}

    public static StringRedisTemplate stringRedisTemplate;

    @Resource
    public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        RedisUtil.stringRedisTemplate = stringRedisTemplate;
    }

    public static Boolean set(String key, String value){
        try {
            stringRedisTemplate.opsForValue().set(key, value);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    public static Boolean set(String key, String value,Long timeOut){
        try {
            stringRedisTemplate.opsForValue().set(key, value,timeOut, TimeUnit.SECONDS);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    public static Boolean delete(String key){
        if(exists(key)){
            return stringRedisTemplate.delete(key);
        }
        return false;
    }

    /** 当指定key和value值一致时才会删除
     * @author lib
     * @date 2021/12/22 14:12
     * @param key key
     * @param value  value
     * @return 0 未删除
     * @since: jdk1.8
     * @update [序号][日期YYYY-MM-DD] [更改人姓名][变更描述]
     */
    public Boolean delete(String key, String value){
        if(exists(key)){
            String deleteKey = "if redis.call(\"get\",KEYS[1]) == ARGV[1] then return redis.call(\"del\",KEYS[1]) else return 0 end";
            DefaultRedisScript<Long> defaultRedisScript = new DefaultRedisScript<>(deleteKey, Long.class);
            Long execute = stringRedisTemplate.execute(defaultRedisScript, Collections.singletonList(key), value);
            return null != execute && execute != 0;
        }
        return false;
    }



    /** 锁定按钮 set nx px
     * @author lib
     * @date 2021/9/15 15:55
     * @param key redis key
     * @param target redis value
     * @param seconds 缓存时间 秒
     * @return false 已锁定 ，ture 已解锁
     * @since: jdk1.8
     * @update [序号][日期YYYY-MM-DD] [更改人姓名][变更描述]
     */
    private Boolean redisLock(String key, String target,Integer seconds) {
        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(key, target, seconds, TimeUnit.SECONDS);
        return aBoolean != null && aBoolean;
    }


    public static boolean exists(final String key) {
        return Boolean.TRUE.equals(stringRedisTemplate.hasKey(key));
    }



}
